/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package goodenglish.application.impl;

import goodenglish.application.SubtImportService;
import goodenglish.domain.model.lexicon.Lexicon;
import goodenglish.domain.model.lexicon.LexiconRepository;
import goodenglish.domain.model.profword.ProfWordLibRepository;
import goodenglish.domain.model.subt.Subt;
import goodenglish.domain.model.subt.SubtFactory;
import goodenglish.domain.model.subt.SubtRepository;
import goodenglish.domain.service.ServiceException;
import goodenglish.domain.service.SubtInType;
import goodenglish.infrastructure.SubtFile;
import goodenglish.infrastructure.repository.db.LexiconRepositoryDb;
import goodenglish.infrastructure.repository.db.ProfWordLibRepositoryDb;
import goodenglish.infrastructure.repository.db.SubtRepositoryDb;
import goodenglish.infrastructure.repository.db.TransactionManager;
import goodenglish.interfaces.BeanFactory;

import java.io.File;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author 关攀攀 panpan_001@126.com
 */
public class SubtImportServiceImpl implements SubtImportService {

	private static Log logger = LogFactory.getLog(SubtImportServiceImpl.class);

	/**
	 * 是否已经导入过
	 * 
	 * @param fileName
	 * @return
	 */
	private boolean isImported(File file) {
		String name = file.getName().split("\\.")[0];
		if (null != subtRepository.getSubtByName(name)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Subt importSubtAndLexicon(File file) throws ServiceException {
		if (this.isImported(file)) {
			// 如果字幕已经导入，提示不可重复导入
			throw new ServiceException("此字幕已导入，不可重复导入！");
		}
		SubtInType subtInType = SubtInType.getImportSubtInType(file);
		Subt subt = subtFactory.createSubt(file, subtInType);
		this.saveSubtAndLexicon(subt);
		return subt;
	}

	@Override
	public void saveSubtAndLexicon(Subt subt) throws ServiceException {
		TransactionManager transactionManager = TransactionManager.getTranManager();
		try {
			Lexicon lexicon = subt.getLexicon();
			transactionManager.beginTransaction();
			lexiconRepository.addLexicon(lexicon);
			subtRepository.saveSubt(subt);
			transactionManager.commit();
		} catch (Exception e) {
			transactionManager.rollback();
			e.printStackTrace();
			throw new ServiceException("保存出错", e);
		}
	}

	private SubtRepository subtRepository = BeanFactory.getSingleInstance(SubtRepositoryDb.class);
	private SubtFile subtFile = BeanFactory.getSingleInstance(SubtFile.class);
	private ProfWordLibRepository profWordsRepository = BeanFactory.getSingleInstance(ProfWordLibRepositoryDb.class);
	private SubtFactory subtFactory = BeanFactory.getSingleInstance(SubtFactory.class);
	private LexiconRepository lexiconRepository = BeanFactory.getSingleInstance(LexiconRepositoryDb.class);

}
